﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using ERP_SaaS_WinForm.物料管理.Material;
using ERP_SaaS_WinForm.生产工单_报工_工序.Process;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using System.Reflection;
using System.Net.Http.Headers;
using ERP_SaaS_WinForm.生产工单_报工_工序;

namespace ERP_SaaS_WinForm.物料管理
{
    public partial class ProcessInspectionForm : CCSkinMain
    {
        private string urls;
        // 存储选中的工单编号
        private string selectedProductionOrderCode = string.Empty;
        // 存储选中的任务信息
        private DispatchTaskInfo selectedTaskInfo = null;
        // 存储所需物料列表
        private List<RequiredMaterial> requiredMaterials = new List<RequiredMaterial>();
        // 检验单编号随机数生成器
        private static readonly Random _randomForInspectionCode = new Random();
        
        /// <summary>
        /// 获取选中的工单编号
        /// </summary>
        public string SelectedProductionOrderCode => selectedProductionOrderCode;
        
        /// <summary>
        /// 获取选中的任务信息
        /// </summary>
        public DispatchTaskInfo SelectedTaskInfo => selectedTaskInfo;
        
        /// <summary>
        /// 获取所需物料列表
        /// </summary>
        public List<RequiredMaterial> RequiredMaterials => requiredMaterials;
        
        public ProcessInspectionForm()
        {
            InitializeComponent();
            InitializeGrid();
            InitializeProductionOrderSelection();
            InitializeTaskSelection(); // 启用任务选择初始化
            InitializeAddInspectionButton(); // 初始化新增质检按钮
            InitializeReworkButton(); // 初始化返工按钮
            urls = Apllo.ApiBaseUrl;
        }

        // 生成检验单编号：JYDBH + 随机四位数字
        private string GenerateInspectionOrderCode()
        {
            return $"JYDBH{_randomForInspectionCode.Next(0, 10000):D4}";
        }

        private async void btnProcessSearch_Click(object sender, EventArgs e)
        {
            await QueryAndBindAsync();
        }

        /// <summary>
        /// 查询并绑定过程质检数据
        /// </summary>
        private async Task QueryAndBindAsync()
        {
            string baseUrl = "http://10.223.8.23:8008/api/ProcessInspection/GetProcessInspection";
            string inspectionOrderCode = txtMaterialCode != null ? txtMaterialCode.Text?.Trim() : string.Empty;
            
            // 如果有搜索条件，添加到URL中
            if (!string.IsNullOrEmpty(inspectionOrderCode))
            {
                baseUrl += $"?inspectionOrderCode={Uri.EscapeDataString(inspectionOrderCode)}";
            }

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(baseUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    
                    // 使用MaterialApiResponse<T>反序列化API响应
                    var apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse<ProcessInspectionDto>>(jsonResponse);
                    
                    if (apiResponse != null && apiResponse.code == 200)
                    {
                        var list = apiResponse.data;
                        if (list != null && list.Count > 0)
                        {
                            // 绑定数据到DataGridView
                            dgvProcessInspection.AutoGenerateColumns = false;
                            dgvProcessInspection.DataSource = list;
                        }
                        else
                        {
                            dgvProcessInspection.DataSource = null;
                            MessageBox.Show("未找到相关数据");
                        }
                    }
                    else
                    {
                        MessageBox.Show($"查询失败: {apiResponse?.message ?? "未知错误"}");
                        dgvProcessInspection.DataSource = null;
                    }
                }
                catch (HttpRequestException ex)
                {
                    MessageBox.Show($"网络请求失败: {ex.Message}");
                    dgvProcessInspection.DataSource = null;
                }
                catch (JsonException ex)
                {
                    MessageBox.Show($"数据解析失败: {ex.Message}");
                    dgvProcessInspection.DataSource = null;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"操作失败: {ex.Message}");
                    dgvProcessInspection.DataSource = null;
                }
            }
        }

        /// <summary>
        /// 初始化DataGridView
        /// </summary>
        private void InitializeGrid()
        {
            // 设置DataGridView属性
            dgvProcessInspection.AutoGenerateColumns = false;
            dgvProcessInspection.AllowUserToAddRows = false;
            dgvProcessInspection.AllowUserToDeleteRows = false;
            dgvProcessInspection.ReadOnly = true;
            dgvProcessInspection.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvProcessInspection.MultiSelect = false;
            
            // 绑定单元格格式化事件
            dgvProcessInspection.CellFormatting += DgvProcessInspection_CellFormatting;

            // 在列表中添加“返工”按钮列（只添加一次）
            if (!dgvProcessInspection.Columns.Contains("Rework"))
            {
                var colRework = new DataGridViewButtonColumn
                {
                    Name = "Rework",
                    HeaderText = "返工",
                    Text = "返工",
                    UseColumnTextForButtonValue = true,
                    Width = 60
                };
                dgvProcessInspection.Columns.Add(colRework);
            }

            // 绑定单元格点击事件处理返工
            dgvProcessInspection.CellClick -= DgvProcessInspection_CellClick;
            dgvProcessInspection.CellClick += DgvProcessInspection_CellClick;
            
            // 绑定搜索按钮事件
            if (btnProcessSearch != null)
            {
                btnProcessSearch.Click -= btnProcessSearch_Click;
                btnProcessSearch.Click += btnProcessSearch_Click;
            }
        }

        /// <summary>
        /// 列表中“返工”按钮点击
        /// </summary>
        private async void DgvProcessInspection_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            if (e.ColumnIndex < 0) return;
            if (dgvProcessInspection.Columns[e.ColumnIndex].Name != "Rework") return;

            var bound = dgvProcessInspection.Rows[e.RowIndex].DataBoundItem;
            if (bound == null)
            {
                MessageBox.Show("未获取到选中记录！");
                return;
            }

            // 获取工单编号
            string productionOrderCode = GetStringProperty(bound, "productionOrderCode");
            if (string.IsNullOrEmpty(productionOrderCode))
            {
                MessageBox.Show("未获取到工单编号，请确认数据源包含 productionOrderCode 字段！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // 直接进行返工处理：根据工单编号更新生产工单为返工状态
            await HandleProductionOrderReworkDirectlyAsync(productionOrderCode);
            await RefreshDataAsync();
        }

        /// <summary>
        /// 处理单元格格式化
        /// </summary>
        private void DgvProcessInspection_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 12 && e.Value != null) // 检验结果列
            {
                if (bool.TryParse(e.Value.ToString(), out bool state))
                {
                    e.Value = state ? "合格" : "不合格";
                    e.FormattingApplied = true;
                }
            }
            else if (e.ColumnIndex == 7 && e.Value != null) // 检验日期列
            {
                if (DateTime.TryParse(e.Value.ToString(), out DateTime date))
                {
                    e.Value = date.ToString("yyyy-MM-dd HH:mm:ss");
                    e.FormattingApplied = true;
                }
            }
        }

        /// <summary>
        /// 刷新数据（供外部或右键菜单调用）
        /// </summary>
        public async Task RefreshDataAsync()
        {
            await QueryAndBindAsync();
        }

        /// <summary>
        /// 初始化工单选择功能
        /// </summary>
        private void InitializeProductionOrderSelection()
        {
            // 为工单编号文本框添加点击事件
            if (txtProductionOrders != null)
            {
                // 先移除，避免重复绑定
                txtProductionOrders.Click -= TxtProductionOrders_Click;
                txtProductionOrders.DoubleClick -= TxtProductionOrders_Click;
                if (txtProductionOrders.SkinTxt != null)
                {
                    txtProductionOrders.SkinTxt.Click -= TxtProductionOrders_Click;
                    txtProductionOrders.SkinTxt.DoubleClick -= TxtProductionOrders_Click;
                }

                // 绑定到外层与内层
                txtProductionOrders.Click += TxtProductionOrders_Click;
                txtProductionOrders.DoubleClick += TxtProductionOrders_Click;
                
                if (txtProductionOrders.SkinTxt != null)
                {
                    txtProductionOrders.SkinTxt.Click += TxtProductionOrders_Click;
                    txtProductionOrders.SkinTxt.DoubleClick += TxtProductionOrders_Click;

                    // 设置只读与手型光标到内层文本框
                    txtProductionOrders.SkinTxt.ReadOnly = true;
                    txtProductionOrders.SkinTxt.Cursor = Cursors.Hand;
                }

                // 设置外层控件的只读与手型光标
                txtProductionOrders.ReadOnly = true; // 设置为只读，防止手动输入
                txtProductionOrders.Cursor = Cursors.Hand; // 设置手型光标，提示可点击
                
                // 添加调试信息
                Console.WriteLine("工单选择功能初始化完成");
            }
            else
            {
                Console.WriteLine("警告: txtProductionOrders 控件未找到");
            }
        }

        /// <summary>
        /// 初始化新增质检按钮
        /// </summary>
        private void InitializeAddInspectionButton()
        {
            if (btnAddinspection != null)
            {
                btnAddinspection.Click -= btnAddinspection_Click;
                btnAddinspection.Click += btnAddinspection_Click;
            }
        }

        /// <summary>
        /// 初始化返工按钮：若设计器无此按钮则运行时创建一个
        /// </summary>
        private void InitializeReworkButton()
        {
            Button btnRework = null;
            // 尝试查找已有按钮
            var found = this.Controls.Find("btnRework", true);
            if (found != null && found.Length > 0)
            {
                btnRework = found[0] as Button;
            }

            if (btnRework == null)
            {
                // 动态创建一个按钮放在右上角（可按需移动到合适位置）
                btnRework = new Button
                {
                    Name = "btnRework",
                    Text = "返工",
                    AutoSize = true,
                    Location = new Point(780, 20)
                };
                this.Controls.Add(btnRework);
            }

            btnRework.Click -= BtnRework_Click;
            btnRework.Click += BtnRework_Click;
        }

        /// <summary>
        /// 返工按钮点击：对选中质检单发起返工
        /// </summary>
        private async void BtnRework_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvProcessInspection == null || dgvProcessInspection.CurrentRow == null)
                {
                    MessageBox.Show("请先选择一条质检记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                var bound = dgvProcessInspection.CurrentRow.DataBoundItem;
                if (bound == null)
                {
                    MessageBox.Show("未获取到选中记录！");
                    return;
                }

                // 获取工单编号
                string productionOrderCode = GetStringProperty(bound, "productionOrderCode");
                if (string.IsNullOrEmpty(productionOrderCode))
                {
                    MessageBox.Show("未获取到工单编号，请确认数据源包含 productionOrderCode 字段！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 直接调用生产工单编辑功能进行返工处理
                await HandleProductionOrderReworkDirectlyAsync(productionOrderCode);
                
                // 刷新质检列表数据
                await RefreshDataAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"返工处理时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private long GetLongProperty(object obj, string[] candidateNames)
        {
            if (obj == null) return 0;
            Type t = obj.GetType();
            foreach (var name in candidateNames)
            {
                var prop = t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                if (prop != null)
                {
                    var v = prop.GetValue(obj);
                    if (v == null) continue;
                    if (v is long l) return l;
                    if (v is int i) return i;
                    if (long.TryParse(v.ToString(), out var p)) return p;
                }
            }
            return 0;
        }

        /// <summary>
        /// 获取字符串属性值
        /// </summary>
        private string GetStringProperty(object obj, string propertyName)
        {
            if (obj == null) return string.Empty;
            Type t = obj.GetType();
            var prop = t.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (prop != null)
            {
                var v = prop.GetValue(obj);
                return v?.ToString() ?? string.Empty;
            }
            return string.Empty;
        }

        private bool PromptReworkInfo(out int quantity, out string reason)
        {
            quantity = 0;
            reason = string.Empty;

            using (var dlg = new Form())
            {
                dlg.Text = "返工信息";
                dlg.StartPosition = FormStartPosition.CenterParent;
                dlg.FormBorderStyle = FormBorderStyle.FixedDialog;
                dlg.MinimizeBox = false;
                dlg.MaximizeBox = false;
                dlg.Size = new Size(360, 200);

                var lblQty = new Label { Text = "返工数量", Location = new Point(20, 25), AutoSize = true };
                var txtQty = new TextBox { Location = new Point(90, 20), Width = 220 };

                var lblReason = new Label { Text = "返工原因", Location = new Point(20, 65), AutoSize = true };
                var txtReason = new TextBox { Location = new Point(90, 60), Width = 220 };

                var btnOk = new Button { Text = "确定", DialogResult = DialogResult.OK, Location = new Point(140, 110), Width = 70 };
                var btnCancel = new Button { Text = "取消", DialogResult = DialogResult.Cancel, Location = new Point(230, 110), Width = 70 };

                dlg.Controls.Add(lblQty);
                dlg.Controls.Add(txtQty);
                dlg.Controls.Add(lblReason);
                dlg.Controls.Add(txtReason);
                dlg.Controls.Add(btnOk);
                dlg.Controls.Add(btnCancel);
                dlg.AcceptButton = btnOk;
                dlg.CancelButton = btnCancel;

                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    if (!int.TryParse(txtQty.Text, out quantity) || quantity <= 0)
                    {
                        MessageBox.Show("请输入有效的返工数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                    reason = (txtReason.Text ?? string.Empty).Trim();
                    return true;
                }
            }
            return false;
        }

        private async Task PerformReworkAsync(long inspectionId, int quantity, string reason)
        {
            try
            {
                string url = "http://10.223.8.23:8008/api/ProcessInspection/Rework";
                var payload = new
                {
                    inspectionId = inspectionId,
                    reworkQuantity = quantity,
                    reworkReason = reason,
                    operatorName = txtInspector?.Text?.Trim() ?? string.Empty,
                    reworkDate = DateTime.Now
                };

                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
                    var resp = await client.PostAsync(url, content);
                    string body = await resp.Content.ReadAsStringAsync();
                    if (resp.IsSuccessStatusCode)
                    {
                        MessageBox.Show("返工提交成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        await RefreshDataAsync();
                    }
                    else
                    {
                        MessageBox.Show($"返工失败: {resp.StatusCode} {body}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"返工发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 直接处理生产工单返工，使用生产工单编辑中的正确API
        /// </summary>
        private async Task HandleProductionOrderReworkDirectlyAsync(string productionOrderCode)
        {
            try
            {
                Console.WriteLine($"开始处理返工请求，工单编号: {productionOrderCode}");
                
                // 1. 根据工单编号查找生产工单
                var productionOrder = await FindProductionOrderByCodeAsync(productionOrderCode);
                if (productionOrder == null)
                {
                    MessageBox.Show($"未找到工单编号为 {productionOrderCode} 的生产工单！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                Console.WriteLine($"找到生产工单: ID={productionOrder.ProductionOrdersId}, 当前状态={productionOrder.State}");

                // 2. 使用生产工单编辑中的正确API更新生产工单状态
                bool updateSuccess = await UpdateProductionOrderForReworkAsync(productionOrder);
                if (updateSuccess)
                {
                    MessageBox.Show($"工单 {productionOrderCode} 返工处理成功！\n\n已更新：\n- 实际数量：0\n- 实际完工：清空\n- 状态：待排产\n- 备注：返工", 
                        "返工成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show($"工单 {productionOrderCode} 返工处理失败！\n\n请查看控制台日志获取详细错误信息。", 
                        "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理返工请求时发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                MessageBox.Show($"处理返工请求时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 根据工单编号查找生产工单
        /// </summary>
        private async Task<ProductionOrders> FindProductionOrderByCodeAsync(string productionOrderCode)
        {
            try
            {
                // 搜索所有页面，直到找到目标工单
                int pageIndex = 1;
                int pageSize = 50; // 使用较大的页面大小减少API调用次数
                int totalSearched = 0;
                
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(30);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    while (true)
                    {
                        string url = urls+$"/api/ProductionOrders/ProductionOrdersCommand?PageIndex={pageIndex}&PageSize={pageSize}";
                        Console.WriteLine($"搜索第 {pageIndex} 页: {url}");
                        
                        var response = await httpClient.GetAsync(url);
                        if (!response.IsSuccessStatusCode)
                        {
                            var errorContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine($"搜索生产工单失败: HTTP {response.StatusCode}, {errorContent}");
                            return null;
                        }

                        var responseContent = await response.Content.ReadAsStringAsync();
                        var apiResponse = JsonConvert.DeserializeObject<ProductionOrdersApiResponse>(responseContent);
                        
                        if (apiResponse?.data?.pageDatas == null || apiResponse.data.pageDatas.Count == 0)
                        {
                            Console.WriteLine($"第 {pageIndex} 页没有数据，停止搜索");
                            break;
                        }

                        // 在当前页面中查找目标工单
                        var targetOrder = apiResponse.data.pageDatas.FirstOrDefault(o => 
                            o.ProductionOrdersCode?.Equals(productionOrderCode, StringComparison.OrdinalIgnoreCase) == true);
                        
                        if (targetOrder != null)
                        {
                            Console.WriteLine($"找到目标工单: ID={targetOrder.ProductionOrdersId}, 编号={targetOrder.ProductionOrdersCode}");
                            return targetOrder;
                        }

                        totalSearched += apiResponse.data.pageDatas.Count;
                        Console.WriteLine($"第 {pageIndex} 页搜索完成，已搜索 {totalSearched} 条记录");
                        
                        // 如果当前页数据量小于页面大小，说明已经是最后一页
                        if (apiResponse.data.pageDatas.Count < pageSize)
                        {
                            Console.WriteLine($"已到达最后一页，停止搜索");
                            break;
                        }
                        
                        pageIndex++;
                        
                        // 防止无限循环，最多搜索100页
                        if (pageIndex > 100)
                        {
                            Console.WriteLine($"搜索页数过多，停止搜索");
                            break;
                        }
                    }
                }
                
                Console.WriteLine($"未找到工单编号为 {productionOrderCode} 的生产工单，总共搜索了 {totalSearched} 条记录");
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查找生产工单时发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return null;
            }
        }

        /// <summary>
        /// 更新生产工单为返工状态，使用生产工单编辑中的正确API
        /// </summary>
        private async Task<bool> UpdateProductionOrderForReworkAsync(ProductionOrders productionOrder)
        {
            try
            {
                Console.WriteLine($"开始更新生产工单为返工状态: ID={productionOrder.ProductionOrdersId}, 编号={productionOrder.ProductionOrdersCode}");
                Console.WriteLine($"当前工单状态: 实际数量={productionOrder.ActualQuantity}, 实际完工={productionOrder.ActualEnd}, 状态={productionOrder.State}");
                
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(30);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // 使用生产工单编辑中的正确数据结构
                    var updateCommand = new ProductionOrdersHandleCommand
                    {
                        // 基本信息
                        ProductionOrdersId = productionOrder.ProductionOrdersId,
                        ProductionOrdersCode = productionOrder.ProductionOrdersCode,
                        ProductionOrdersName = productionOrder.ProductionOrdersName,
                        
                        // 返工状态更新
                        ActualQuantity = 0, // 实际数量设为0
                        ActualEnd = null, // 实际完工时间清空为null
                        State = 0, // 状态设为待排产
                        ProductionOrdersProgress = 0, // 工单进度设为0
                        
                        // 保持其他字段不变
                        PlannedQuantity = productionOrder.PlannedQuantity,
                        PlanStart = productionOrder.PlanStart?.ToString("yyyy-MM-ddTHH:mm:ss") ?? "",
                        PlanEnd = productionOrder.PlanEnd?.ToString("yyyy-MM-ddTHH:mm:ss") ?? "",
                        DemandDate = productionOrder.DemandDate?.ToString("yyyy-MM-ddTHH:mm:ss") ?? "",
                        ActualStart = productionOrder.ActualStart?.ToString("yyyy-MM-ddTHH:mm:ss") ?? "",
                        Remark = "返工", // 备注设置为返工
                       
                        // 产品信息
                        BOM = productionOrder.BOM ?? "",
                        Type = productionOrder.Type ?? "",
                        Unit = productionOrder.Unit ?? "",
                        Version = productionOrder.Version ?? "",
                        PlanNumber = productionOrder.PlanNumber ?? "",
                        ProductCode = productionOrder.ProductCode ?? "",
                        ProductName = productionOrder.ProductName ?? "",
                        ProductType = productionOrder.ProductType ?? "",
                        AssociatePlans = productionOrder.AssociatePlans ?? "",
                        SpecificationModel = productionOrder.SpecificationModel ?? "",
                        Batch = productionOrder.Batch ?? "",
                        CreateBy = "System"
                    };

                    var jsonContent = JsonConvert.SerializeObject(updateCommand);
                    Console.WriteLine(urls+$"发送更新请求到: /api/ProductionOrders/Handle");
                    Console.WriteLine($"请求内容: {jsonContent}");
                    
                    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                    Console.WriteLine($"开始发送POST请求...");
                    
                    var response = await httpClient.PostAsync(urls+"/api/ProductionOrders/Handle", content);
                    Console.WriteLine($"收到响应: {response.StatusCode}");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"更新成功，响应内容: {responseContent}");
                        
                        // 验证更新是否真的成功
                        Console.WriteLine("等待数据库更新...");
                        await Task.Delay(2000); // 等待2秒让数据库更新
                        
                        // 重新查询工单状态确认更新
                        Console.WriteLine("重新查询工单状态验证更新结果...");
                        var updatedOrder = await FindProductionOrderByCodeAsync(productionOrder.ProductionOrdersCode);
                        if (updatedOrder != null)
                        {
                            Console.WriteLine($"=== 验证更新结果 ===");
                            Console.WriteLine($"更新后状态: 实际数量={updatedOrder.ActualQuantity}, 实际完工={updatedOrder.ActualEnd}, 状态={updatedOrder.State}, 备注={updatedOrder.Remark}");
                            
                            if (updatedOrder.ActualQuantity == 0 && updatedOrder.State == 0 && updatedOrder.Remark == "返工")
                            {
                                Console.WriteLine("✅ 返工更新验证成功！所有字段都已正确更新");
                                return true;
                            }
                            else
                            {
                                Console.WriteLine("⚠️ 返工更新验证失败，字段未按预期更新");
                                Console.WriteLine($"期望: 实际数量=0, 状态=0, 备注=返工");
                                Console.WriteLine($"实际: 实际数量={updatedOrder.ActualQuantity}, 状态={updatedOrder.State}, 备注={updatedOrder.Remark}");
                                return false;
                            }
                        }
                        else
                        {
                            Console.WriteLine("⚠️ 无法重新查询工单，无法验证更新结果");
                            return true; // 假设更新成功
                        }
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"更新失败: HTTP {response.StatusCode}");
                        Console.WriteLine($"错误响应内容: {errorContent}");
                        MessageBox.Show($"返工失败：HTTP {response.StatusCode}\n{errorContent}", "返工失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Console.WriteLine(urls+$"请求URL: /api/ProductionOrders/Handle");
                        Console.WriteLine($"请求内容: {jsonContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新生产工单时发生异常: {ex.Message}");
                Console.WriteLine($"异常类型: {ex.GetType().Name}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return false;
            }
        }

        /// <summary>
        /// 初始化工单选择功能
        /// </summary>
        private void InitializeTaskSelection()
        {
            // 为任务名称文本框添加点击事件
            if (txtDispatchCode != null)
            {
                // 先移除，避免重复绑定
                txtDispatchCode.Click -= TxtDispatchCode_Click;
                txtDispatchCode.DoubleClick -= TxtDispatchCode_Click;
                if (txtDispatchCode.SkinTxt != null)
                {
                    txtDispatchCode.SkinTxt.Click -= TxtDispatchCode_Click;
                    txtDispatchCode.SkinTxt.DoubleClick -= TxtDispatchCode_Click;
                }

                // 绑定到外层与内层
                txtDispatchCode.Click += TxtDispatchCode_Click;
                txtDispatchCode.DoubleClick += TxtDispatchCode_Click;
                
                if (txtDispatchCode.SkinTxt != null)
                {
                    txtDispatchCode.SkinTxt.Click += TxtDispatchCode_Click;
                    txtDispatchCode.SkinTxt.DoubleClick += TxtDispatchCode_Click;

                    // 设置只读与手型光标到内层文本框
                    txtDispatchCode.SkinTxt.ReadOnly = true;
                    txtDispatchCode.SkinTxt.Cursor = Cursors.Hand;
                }

                // 设置外层控件的只读与手型光标
                txtDispatchCode.ReadOnly = true; // 设置为只读，防止手动输入
                txtDispatchCode.Cursor = Cursors.Hand; // 设置手型光标，提示可点击
                
                // 添加调试信息
                Console.WriteLine("任务选择功能初始化完成");
            }
            else
            {
                Console.WriteLine("警告: txtDispatchCode 控件未找到");
            }
        }

        /// <summary>
        /// 工单编号文本框点击事件
        /// </summary>
        private void TxtProductionOrders_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建并显示工单选择窗体
                SelectProductionOrderForm selectForm = new SelectProductionOrderForm();
                
                // 显示对话框并获取结果
                if (selectForm.ShowDialog() == DialogResult.OK)
                {
                    // 获取选中的工单
                    var selectedProductionOrder = selectForm.SelectedProductionOrder;
                    if (selectedProductionOrder != null)
                    {
                                                 // 更新工单编号字段，显示工单编号
                         txtProductionOrders.Text = selectedProductionOrder.ProductionOrdersCode;
                         
                         // 保存工单编号到私有字段中
                         selectedProductionOrderCode = selectedProductionOrder.ProductionOrdersCode;
                         
                         // 显示选择成功的信息
                         MessageBox.Show($"已选择工单编号: {selectedProductionOrder.ProductionOrdersCode}", 
                             "工单选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        // 注意：不更新检验单编号和检验单名称，这些是独立的字段
                        // 不更新txtOrderCode和txtOrderName，保持它们的独立性
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开工单选择页面失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 任务名称文本框点击事件
        /// </summary>
        private async void TxtDispatchCode_Click(object sender, EventArgs e)
        {
            await SelectTaskAsync();
        }

        /// <summary>
        /// 任务选择方法（可以通过按钮调用）
        /// </summary>
        public async Task SelectTaskAsync()
        {
            try
            {
                // 调用Dispatch API获取任务列表
                await LoadDispatchTasksAsync();
                
                // 创建并显示任务选择窗体
                SelectTaskForm selectForm = new SelectTaskForm(requiredMaterials);
                
                // 显示对话框并获取结果
                if (selectForm.ShowDialog() == DialogResult.OK)
                {
                    // 获取选中的任务
                    var selectedTask = selectForm.SelectedTask;
                    if (selectedTask != null)
                    {
                                                 // 更新任务编号字段（保存编号）
                         txtDispatchCode.Text = selectedTask.taskCode;
                         
                         // 保存选中的任务信息
                         // 将RequiredMaterial转换为DispatchTaskInfo
                         selectedTaskInfo = new DispatchTaskInfo
                         {
                             taskId = selectedTask.taskId,
                             taskCode = selectedTask.taskCode,
                             taskName = selectedTask.taskName,
                             productId = selectedTask.productId,
                             productName = selectedTask.productName,
                             specification = selectedTask.specification,
                             unitName = selectedTask.unitName,
                             materialId = selectedTask.materialId,
                             materialName = selectedTask.materialName,
                             teamId = selectedTask.teamId,
                             teamName = selectedTask.teamName,
                             leader = selectedTask.leader,
                             name = selectedTask.name,
                             siteId = selectedTask.siteId,
                             siteName = selectedTask.siteName,
                             carId = selectedTask.carId,
                             carName = selectedTask.carName,
                             lineId = selectedTask.lineId,
                             lineName = selectedTask.lineName,
                             processId = selectedTask.processId,
                             taskState = selectedTask.taskState
                         };
                         
                         // 显示选择成功的信息
                         MessageBox.Show($"已选择任务编号: {selectedTask.taskCode}", 
                             "任务选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开任务选择页面失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载Dispatch任务数据
        /// </summary>
        private async Task LoadDispatchTasksAsync()
        {
            try
            {
                string url = "http://10.223.8.13:7777/api/Dispatch/GetDispatch";
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResponse = await response.Content.ReadAsStringAsync();
                        var apiResponse = JsonConvert.DeserializeObject<DispatchApiResponse>(jsonResponse);
                        
                        if (apiResponse?.code == 200 && apiResponse.data != null)
                        {
                            // 清空并重新填充所需物料列表
                            requiredMaterials.Clear();
                            foreach (var task in apiResponse.data)
                            {
                                requiredMaterials.Add(new RequiredMaterial
                                {
                                    taskId = task.taskId,
                                    taskCode = task.taskCode,
                                    taskName = task.taskName,
                                    productId = task.productId,
                                    productName = task.productName,
                                    specification = task.specification,
                                    unitName = task.unitName,
                                    materialId = task.materialId,
                                    materialName = task.materialName,
                                    teamId = task.teamId,
                                    teamName = task.teamName,
                                    leader = task.leader,
                                    name = task.name,
                                    siteId = task.siteId,
                                    siteName = task.siteName,
                                    carId = task.carId,
                                    carName = task.carName,
                                    lineId = task.lineId,
                                    lineName = task.lineName,
                                    processId = task.processId,
                                    taskState = task.taskState
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载Dispatch任务数据失败: {ex.Message}");
            }
        }

        // Designer 绑定的 Load 事件
        private async void ProcessInspectionForm_Load_1(object sender, EventArgs e)
        {
            // 避免重复初始化
            if (dgvProcessInspection.DataSource == null)
            {
                InitializeGrid();
                await QueryAndBindAsync();
            }
            // 初始化时自动生成一次检验单编号（若为空）
            if (txtOrderCode != null && string.IsNullOrWhiteSpace(txtOrderCode.Text))
            {
                txtOrderCode.Text = GenerateInspectionOrderCode();
            }
        }

        /// <summary>
        /// 新增质检按钮点击事件
        /// </summary>
        private async void btnAddinspection_Click(object sender, EventArgs e)
        {
            await CreateProcessInspectionAsync();
        }

        /// <summary>
        /// 创建过程质检单
        /// </summary>
        private async Task CreateProcessInspectionAsync()
        {
            try
            {
                // 验证必填字段
                if (!ValidateRequiredFields())
                {
                    return;
                }

                // 添加调试信息
                Console.WriteLine($"=== 质检确认调试信息 ===");
                Console.WriteLine($"selectedProductionOrderCode: '{selectedProductionOrderCode}'");
                Console.WriteLine($"txtProductionOrders.Text: '{txtProductionOrders?.Text}'");
                Console.WriteLine($"selectedTaskInfo?.taskId: {selectedTaskInfo?.taskId}");
                Console.WriteLine($"txtQuantity.Text: '{txtQuantity?.Text}'");
                Console.WriteLine($"txtGoodQuantity.Text: '{txtGoodQuantity?.Text}'");

                // 创建请求对象 - 使用基本字段，避免复杂的字段映射
                var requestData = new CreateProcessInspectionRequest
                {
                    inspectionOrderCode = txtOrderCode?.Text?.Trim(),
                    inspectionOrderName = txtOrderName?.Text?.Trim(),
                    inspectionDate = GetDateTimeValue(dtpinspectionDate?.text) ?? DateTime.Now,
                    inspector = txtInspector?.Text?.Trim(),
                    productionOrderCode = selectedProductionOrderCode,
                    dispatchId = selectedTaskInfo?.taskId ?? 0,
                    inspectionQuantity = GetIntValue(txtQuantity?.Text),
                    qualifiedQuantity = GetIntValue(txtGoodQuantity?.Text),
                    unqualifiedQuantity = GetIntValue(txtQuantity?.Text) - GetIntValue(txtGoodQuantity?.Text),
                    
                    // 简化产品信息字段
                    productCode = "",
                    productName = "",
                    specification = "",
                    unit = "",
                    state = true
                };


                // 调用API创建质检单
                string url = "http://10.223.8.23:8008/api/ProcessInspection/CreateProcessInspection";
                using (HttpClient client = new HttpClient())
                {
                    var jsonContent = JsonConvert.SerializeObject(requestData);
                    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");            
                    
                     HttpResponseMessage response = await client.PostAsync(url, content);
                     
                     // 显示响应状态码
                     Console.WriteLine($"HTTP响应状态码: {response.StatusCode}");
                     Console.WriteLine($"响应头: {response.Headers}");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResponse = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API响应内容: {jsonResponse}");
                        
                        // 检查响应内容是否为空
                        if (string.IsNullOrWhiteSpace(jsonResponse))
                        {
                            string errorMessage = "新增失败:\nAPI响应为空，请检查服务器端配置";
                            Console.WriteLine(errorMessage);
                            MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        
                        // 尝试解析API响应
                        try
                        {
                            var apiResponse = JsonConvert.DeserializeObject<CreateProcessInspectionResponse>(jsonResponse);
                            
                            if (apiResponse != null)
                            {
                                Console.WriteLine($"解析后的API响应: code={apiResponse.code}, msg='{apiResponse.msg}'");
                                
                                if (apiResponse.code == 200)
                                {
                                    MessageBox.Show("新增质检单成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    
                                    // 添加调试信息
                                    Console.WriteLine($"=== 质检单创建成功，准备更新生产工单 ===");
                                    Console.WriteLine($"工单编号: {requestData.productionOrderCode}");
                                    Console.WriteLine($"合格数量: {requestData.qualifiedQuantity}");
                                    Console.WriteLine($"检验数量: {requestData.inspectionQuantity}");
                                    
                                    // 自动更新生产工单的实际数量、实际完工时间和状态
                                    bool updateSuccess = await UpdateProductionOrderAfterInspectionAsync(requestData);
                                    
                                    // 清空表单
                                    ClearForm();
                                    
                                    // 刷新列表
                                    await RefreshDataAsync();
                                    
                                    // 如果更新成功，提示用户刷新生产工单列表
                                    if (updateSuccess)
                                    {
                                        MessageBox.Show("质检确认完成！\n\n生产工单数据已更新：\n- 实际数量已更新为合格数量\n- 实际完工时间已更新为当前时间\n- 工单进度已更新为100%\n- 状态已根据完工时间自动判断\n\n请在生产工单管理页面点击刷新按钮查看最新数据。", 
                                            "更新成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                }
                                else
                                {
                                    string errorMessage = $"新增失败:\n状态码: {apiResponse.code}\n消息: {apiResponse.msg ?? "未知错误"}";
                                    Console.WriteLine(errorMessage);
                                    MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                            else
                            {
                                string errorMessage = $"新增失败:\nAPI响应解析失败，响应内容: {jsonResponse}";
                                Console.WriteLine(errorMessage);
                                MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        catch (JsonException jsonEx)
                        {
                            string errorMessage = $"新增失败:\nJSON解析异常: {jsonEx.Message}\n原始响应: {jsonResponse}";
                            Console.WriteLine(errorMessage);
                            MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        string errorContent = await response.Content.ReadAsStringAsync();
                        string errorMessage = $"HTTP请求失败:\n状态码: {response.StatusCode}\n错误内容: {errorContent}";
                        Console.WriteLine(errorMessage);
                        MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMessage = $"创建质检单失败:\n异常类型: {ex.GetType().Name}\n异常信息: {ex.Message}\n堆栈跟踪: {ex.StackTrace}";
                Console.WriteLine(errorMessage);
                MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 验证必填字段
        /// </summary>
        private bool ValidateRequiredFields()
        {
            if (string.IsNullOrWhiteSpace(txtOrderCode?.Text))
            {
                MessageBox.Show("请填写检验单编号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtOrderCode.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtOrderName?.Text))
            {
                MessageBox.Show("请填写检验单名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtOrderName.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(selectedProductionOrderCode))
            {
                MessageBox.Show("请选择工单！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtProductionOrders.Focus();
                return false;
            }

            if (selectedTaskInfo == null)
            {
                MessageBox.Show("请选择任务！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtDispatchCode.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtInspector?.Text))
            {
                MessageBox.Show("请填写检验人！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtInspector.Focus();
                return false;
            }

            int inspectionQuantity = GetIntValue(txtQuantity?.Text);
            if (inspectionQuantity <= 0)
            {
                MessageBox.Show("请填写有效的检验数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtQuantity.Focus();
                return false;
            }

            int qualifiedQuantity = GetIntValue(txtGoodQuantity?.Text);
            if (qualifiedQuantity < 0 || qualifiedQuantity > inspectionQuantity)
            {
                MessageBox.Show("合格数量不能小于0或大于检验数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtGoodQuantity.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 获取整数值
        /// </summary>
        private int GetIntValue(string value)
        {
            if (int.TryParse(value, out int result))
            {
                return result;
            }
            return 0;
        }

        /// <summary>
        /// 获取日期时间值
        /// </summary>
        private DateTime? GetDateTimeValue(string value)
        {
            if (DateTime.TryParse(value, out DateTime result))
            {
                return result;
            }
            return null;
        }

        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            txtOrderCode.Text = GenerateInspectionOrderCode();
            txtOrderName.Text = string.Empty;
            txtInspector.Text = string.Empty;
            txtQuantity.Text = string.Empty;
            txtGoodQuantity.Text = string.Empty;
            dtpinspectionDate.text = DateTime.Now.ToString("yyyy-MM-dd");
            
            // 清空选择的数据
            selectedProductionOrderCode = string.Empty;
            selectedTaskInfo = null;
            requiredMaterials.Clear();
            
            // 清空显示
            txtProductionOrders.Text = string.Empty;
            txtDispatchCode.Text = string.Empty;
        }

        /// <summary>
        /// 质检确认后自动更新生产工单的实际数量、实际完工时间和状态
        /// </summary>
        private async Task<bool> UpdateProductionOrderAfterInspectionAsync(CreateProcessInspectionRequest inspectionData)
        {
            try
            {
                Console.WriteLine("=== 开始更新生产工单 ===");
                Console.WriteLine($"质检数据: 工单编号={inspectionData.productionOrderCode}, 合格数量={inspectionData.qualifiedQuantity}");
                
                if (string.IsNullOrWhiteSpace(inspectionData.productionOrderCode))
                {
                    Console.WriteLine("生产工单编号为空，跳过更新");
                    return false;
                }

                // 先获取生产工单的ID
                int productionOrderId = await GetProductionOrderIdByCodeAsync(inspectionData.productionOrderCode);
                if (productionOrderId == 0)
                {
                    Console.WriteLine($"未找到生产工单: {inspectionData.productionOrderCode}");
                    MessageBox.Show($"未找到生产工单: {inspectionData.productionOrderCode}\n请检查工单编号是否正确。", 
                        "工单未找到", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

                Console.WriteLine($"成功获取生产工单ID: {productionOrderId}");

                // 先获取生产工单的完整信息
                var productionOrderInfo = await GetProductionOrderInfoAsync(inspectionData.productionOrderCode);
                if (productionOrderInfo == null)
                {
                    Console.WriteLine($"无法获取生产工单详细信息: {inspectionData.productionOrderCode}");
                    MessageBox.Show($"无法获取生产工单详细信息: {inspectionData.productionOrderCode}", 
                        "获取工单信息失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

                // 判断状态：如果完工时间超过需求时间，状态为已暂停，否则为已完成
                int stateValue;
                string stateDescription;
                DateTime currentTime = DateTime.Now;
                
                if (productionOrderInfo.DemandDate.HasValue && currentTime > productionOrderInfo.DemandDate.Value)
                {
                    stateValue = 4; // 已暂停状态
                    stateDescription = "已暂停";
                    Console.WriteLine($"完工时间({currentTime:yyyy-MM-dd HH:mm})超过需求时间({productionOrderInfo.DemandDate.Value:yyyy-MM-dd HH:mm})，状态设置为已暂停");
                }
                else
                {
                    stateValue = 3; // 已完成状态
                    stateDescription = "已完成";
                    Console.WriteLine($"完工时间({currentTime:yyyy-MM-dd HH:mm})未超过需求时间({productionOrderInfo.DemandDate?.ToString("yyyy-MM-dd HH:mm") ?? "无"}，状态设置为已完成");
                }

                // 构建更新生产工单的请求 - 使用ProductionOrdersHandleCommand类
                var updateRequest = new ProductionOrdersHandleCommand
                {
                    ProductionOrdersId = productionOrderId,
                    ProductionOrdersCode = inspectionData.productionOrderCode,
                    ProductionOrdersName = productionOrderInfo.ProductionOrdersName,
                    ActualQuantity = inspectionData.qualifiedQuantity, // 设置实际数量为合格数量
                    ActualEnd = currentTime.ToString("yyyy-MM-ddTHH:mm:ss"), // 设置实际完工时间为当前时间
                    ProductionOrdersProgress = 100, // 设置工单进度为100%
                    State = stateValue, // 根据完工时间判断状态
                    Remark = $"质检确认完成\n合格数量：{inspectionData.qualifiedQuantity}\n不合格数量：{inspectionData.unqualifiedQuantity}\n检验日期：{inspectionData.inspectionDate:yyyy-MM-dd HH:mm}\n状态：{stateDescription}\n工单进度：100%",
                    CreateBy = !string.IsNullOrWhiteSpace(Environment.UserName) ? Environment.UserName : "System",
                    
                    // 从原工单信息复制其他必需字段
                    BOM = productionOrderInfo.BOM,
                    Type = productionOrderInfo.Type,
                    Unit = productionOrderInfo.Unit,
                    Version = productionOrderInfo.Version,
                    PlanNumber = productionOrderInfo.PlanNumber,
                    ProductCode = productionOrderInfo.ProductCode,
                    ProductName = productionOrderInfo.ProductName,
                    ProductType = productionOrderInfo.ProductType,
                    AssociatePlans = productionOrderInfo.AssociatePlans,
                    SpecificationModel = productionOrderInfo.SpecificationModel,
                    Batch = productionOrderInfo.Batch,
                    
                    // 保持原有的计划信息
                    PlannedQuantity = productionOrderInfo.PlannedQuantity,
                    PlanStart = productionOrderInfo.PlanStart?.ToString("yyyy-MM-ddTHH:mm:ss"),
                    PlanEnd = productionOrderInfo.PlanEnd?.ToString("yyyy-MM-ddTHH:mm:ss"),
                    DemandDate = productionOrderInfo.DemandDate?.ToString("yyyy-MM-ddTHH:mm:ss"),
                    ActualStart = productionOrderInfo.ActualStart?.ToString("yyyy-MM-ddTHH:mm:ss")
                };

                Console.WriteLine($"准备更新生产工单: {inspectionData.productionOrderCode}, ID: {productionOrderId}");
                Console.WriteLine($"更新数据: {JsonConvert.SerializeObject(updateRequest)}");

                // 调用生产工单更新API - 使用Handle端点
                string updateUrl = urls+"/api/ProductionOrders/Handle";
                using (HttpClient client = new HttpClient())
                {
                    var jsonContent = JsonConvert.SerializeObject(updateRequest);
                    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    Console.WriteLine($"发送更新请求到: {updateUrl}");
                    Console.WriteLine($"更新请求JSON: {jsonContent}");

                    HttpResponseMessage response = await client.PostAsync(updateUrl, content);

                    Console.WriteLine($"更新响应状态码: {response.StatusCode}");

                    if (response.IsSuccessStatusCode)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"更新响应内容: {responseContent}");

                        // 显示成功提示
                        string successMessage = $"生产工单更新成功！\n" +
                            $"工单编号：{inspectionData.productionOrderCode}\n" +
                            $"实际数量：{inspectionData.qualifiedQuantity}\n" +
                            $"实际完工时间：{currentTime:yyyy-MM-dd HH:mm}\n" +
                            $"工单进度：100%\n" +
                            $"工单状态：{stateDescription}";

                        MessageBox.Show(successMessage, "生产工单更新成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Console.WriteLine("=== 生产工单更新完成 ===");
                        return true;
                    }
                    else
                    {
                        string errorContent = await response.Content.ReadAsStringAsync();
                        string errorMessage = $"更新生产工单失败:\n状态码: {response.StatusCode}\n错误内容: {errorContent}";
                        Console.WriteLine(errorMessage);

                        // 显示警告，但不阻止质检流程
                        MessageBox.Show($"质检单创建成功，但生产工单更新失败:\n{errorMessage}\n\n请手动更新生产工单状态。",
                            "部分成功", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMessage = $"更新生产工单时发生异常:\n异常类型: {ex.GetType().Name}\n异常信息: {ex.Message}";
                Console.WriteLine(errorMessage);
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");

                // 显示警告，但不阻止质检流程
                MessageBox.Show($"质检单创建成功，但生产工单更新时发生错误:\n{ex.Message}\n\n请手动更新生产工单状态。",
                    "部分成功", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
        }

        /// <summary>
        /// 根据工单编号获取生产工单完整信息
        /// </summary>
        private async Task<ProductionOrders> GetProductionOrderInfoAsync(string productionOrderCode)
        {
            try
            {
                // 搜索多个页面，直到找到目标工单
                int pageIndex = 1;
                int pageSize = 100;
                
                using (HttpClient client = new HttpClient())
                {
                    while (pageIndex <= 10) // 最多搜索10页
                    {
                        string url = urls+$"/api/ProductionOrders/ProductionOrdersCommand?PageIndex={pageIndex}&PageSize={pageSize}";
                        Console.WriteLine($"正在获取生产工单信息，搜索编号: {productionOrderCode}，第{pageIndex}页");
                        Console.WriteLine($"请求URL: {url}");
                        
                        var response = await client.GetAsync(url);
                        Console.WriteLine($"获取生产工单列表响应状态码: {response.StatusCode}");
                        
                        if (response.IsSuccessStatusCode)
                        {
                            string jsonResponse = await response.Content.ReadAsStringAsync();
                            Console.WriteLine($"生产工单列表响应内容: {jsonResponse}");
                            
                            var apiResponse = JsonConvert.DeserializeObject<ProductionOrdersApiResponse>(jsonResponse);
                            
                                                    // 使用与ProcessForm相同的逻辑处理不同的API响应格式
                        var items = apiResponse?.data?.pageDatas ?? apiResponse?.data?.data;
                        if (items != null && items.Count > 0)
                        {
                            Console.WriteLine($"第{pageIndex}页找到 {items.Count} 个生产工单");
                            
                            var productionOrder = items.FirstOrDefault(p => 
                                p.ProductionOrdersCode == productionOrderCode);
                            
                            if (productionOrder != null)
                            {
                                Console.WriteLine($"找到匹配的生产工单: ID={productionOrder.ProductionOrdersId}, Code={productionOrder.ProductionOrdersCode}");
                                return productionOrder;
                            }
                            else
                            {
                                Console.WriteLine($"第{pageIndex}页未找到匹配的生产工单编号: {productionOrderCode}");
                                // 打印当前页面的工单编号用于调试
                                foreach (var po in items)
                                {
                                    Console.WriteLine($"第{pageIndex}页可用工单: {po.ProductionOrdersCode}");
                                }
                                
                                // 如果当前页数据少于pageSize，说明已经是最后一页
                                if (items.Count < pageSize)
                                {
                                    Console.WriteLine($"已到达最后一页，停止搜索");
                                    break;
                                }
                            }
                        }
                            else
                            {
                                Console.WriteLine($"第{pageIndex}页API响应中没有data字段或data为空");
                                break; // 没有数据了，停止搜索
                            }
                        }
                        else
                        {
                            string errorContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine($"获取生产工单列表失败: {response.StatusCode}, {errorContent}");
                            break;
                        }
                        
                        pageIndex++;
                    }
                }
                
                Console.WriteLine($"在所有页面中都未找到生产工单编号: {productionOrderCode}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取生产工单信息失败: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
            
            return null;
        }

        /// <summary>
        /// 根据工单编号获取生产工单ID
        /// </summary>
        private async Task<int> GetProductionOrderIdByCodeAsync(string productionOrderCode)
        {
            try
            {
                // 搜索多个页面，直到找到目标工单
                int pageIndex = 1;
                int pageSize = 100;
                
                using (HttpClient client = new HttpClient())
                {
                    while (pageIndex <= 10) // 最多搜索10页
                    {
                        string url = urls+$"/api/ProductionOrders/ProductionOrdersCommand?PageIndex={pageIndex}&PageSize={pageSize}";
                        Console.WriteLine($"正在获取生产工单ID，搜索编号: {productionOrderCode}，第{pageIndex}页");
                        Console.WriteLine($"请求URL: {url}");
                        
                        var response = await client.GetAsync(url);
                        Console.WriteLine($"获取生产工单列表响应状态码: {response.StatusCode}");
                        
                        if (response.IsSuccessStatusCode)
                        {
                            string jsonResponse = await response.Content.ReadAsStringAsync();
                            Console.WriteLine($"生产工单列表响应内容: {jsonResponse}");
                            
                            var apiResponse = JsonConvert.DeserializeObject<ProductionOrdersApiResponse>(jsonResponse);
                            
                                                    // 使用与ProcessForm相同的逻辑处理不同的API响应格式
                        var items = apiResponse?.data?.pageDatas ?? apiResponse?.data?.data;
                        if (items != null && items.Count > 0)
                        {
                            Console.WriteLine($"第{pageIndex}页找到 {items.Count} 个生产工单");
                            
                            var productionOrder = items.FirstOrDefault(p => 
                                p.ProductionOrdersCode == productionOrderCode);
                            
                            if (productionOrder != null)
                            {
                                Console.WriteLine($"找到匹配的生产工单: ID={productionOrder.ProductionOrdersId}, Code={productionOrder.ProductionOrdersCode}");
                                return productionOrder.ProductionOrdersId;
                            }
                            else
                            {
                                Console.WriteLine($"第{pageIndex}页未找到匹配的生产工单编号: {productionOrderCode}");
                                // 打印当前页面的工单编号用于调试
                                foreach (var po in items)
                                {
                                    Console.WriteLine($"第{pageIndex}页可用工单: {po.ProductionOrdersCode}");
                                }
                                
                                // 如果当前页数据少于pageSize，说明已经是最后一页
                                if (items.Count < pageSize)
                                {
                                    Console.WriteLine($"已到达最后一页，停止搜索");
                                    break;
                                }
                            }
                        }
                            else
                            {
                                Console.WriteLine($"第{pageIndex}页API响应中没有data字段或data为空");
                                break; // 没有数据了，停止搜索
                            }
                        }
                        else
                        {
                            string errorContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine($"获取生产工单列表失败: {response.StatusCode}, {errorContent}");
                            break;
                        }
                        
                        pageIndex++;
                    }
                }
                
                Console.WriteLine($"在所有页面中都未找到生产工单编号: {productionOrderCode}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取生产工单ID失败: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
            
            return 0;
        }

        private void btnAddinspection_Click_1(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 直接传递工单编号给生产工单
        /// </summary>
        private async Task SendProductionOrderCodeToProductionOrderAsync(string productionOrderCode)
        {
            try
            {
                // 打开生产工单窗体并定位到对应工单
                await OpenProductionOrderFormAndLocateOrderAsync(productionOrderCode);
                
                // 刷新质检列表数据
                await RefreshDataAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开生产工单时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 打开生产工单窗体并定位到对应工单
        /// </summary>
        private async Task OpenProductionOrderFormAndLocateOrderAsync(string productionOrderCode)
        {
            try
            {
                // 查找并打开生产工单窗体
                var processForm = Application.OpenForms.OfType<ERP_SaaS_WinForm.生产工单_报工_工序.ProcessForm>().FirstOrDefault();
                
                if (processForm == null)
                {
                    // 如果生产工单窗体未打开，则创建新实例
                    processForm = new ERP_SaaS_WinForm.生产工单_报工_工序.ProcessForm();
                    processForm.Show();
                }
                else
                {
                    // 如果窗体已打开，则激活它
                    processForm.Activate();
                }

                // 等待窗体加载完成
                await Task.Delay(500);
                
                // 切换到生产工单面板并搜索定位工单
                await processForm.SwitchToProductionOrdersAndLocateAsync(productionOrderCode);
                
                Console.WriteLine($"生产工单窗体打开并定位完成: {productionOrderCode}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"打开生产工单窗体时发生异常: {ex.Message}");
                MessageBox.Show($"打开生产工单窗体失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    /// <summary>
    /// 生产工单API响应
    /// </summary>
    public class ProductionOrdersApiResponse
    {
        [JsonProperty("code")]
        public int code { get; set; }
        [JsonProperty("message")]
        public string message { get; set; }
        [JsonProperty("data")]
        public ProductionOrdersData data { get; set; }
    }

    /// <summary>
    /// 生产工单数据
    /// </summary>
    public class ProductionOrdersData
    {
        [JsonProperty("pageDatas")]
        public List<ProductionOrders> pageDatas { get; set; }
        [JsonProperty("data")]
        public List<ProductionOrders> data { get; set; }
        [JsonProperty("totalCount")]
        public int totalCount { get; set; }
        [JsonProperty("totalPage")]
        public int totalPage { get; set; }
        [JsonProperty("pageIndex")]
        public int pageIndex { get; set; }
        [JsonProperty("pageSize")]
        public int pageSize { get; set; }
    }

    /// <summary>
    /// 生产工单
    /// </summary>
    public class ProductionOrders
    {
        [JsonProperty("productionOrdersId")]
        public int ProductionOrdersId { get; set; }
        [JsonProperty("productionOrdersCode")]
        public string ProductionOrdersCode { get; set; }
        [JsonProperty("productionOrdersName")]
        public string ProductionOrdersName { get; set; }
        [JsonProperty("state")]
        public int State { get; set; }
        [JsonProperty("actualQuantity")]
        public int ActualQuantity { get; set; }
        [JsonProperty("actualEnd")]
        public DateTime? ActualEnd { get; set; }
        [JsonProperty("remark")]
        public string Remark { get; set; }
        
        // 添加其他必需字段
        [JsonProperty("bom")]
        public string BOM { get; set; }
        [JsonProperty("type")]
        public string Type { get; set; }
        [JsonProperty("unit")]
        public string Unit { get; set; }
        [JsonProperty("version")]
        public string Version { get; set; }
        [JsonProperty("planNumber")]
        public string PlanNumber { get; set; }
        [JsonProperty("productCode")]
        public string ProductCode { get; set; }
        [JsonProperty("productName")]
        public string ProductName { get; set; }
        [JsonProperty("productType")]
        public string ProductType { get; set; }
        [JsonProperty("associatePlans")]
        public string AssociatePlans { get; set; }
        [JsonProperty("specificationModel")]
        public string SpecificationModel { get; set; }
        [JsonProperty("batch")]
        public string Batch { get; set; }
        [JsonProperty("plannedQuantity")]
        public int PlannedQuantity { get; set; }
        [JsonProperty("planStart")]
        public DateTime? PlanStart { get; set; }
        [JsonProperty("planEnd")]
        public DateTime? PlanEnd { get; set; }
        [JsonProperty("demandDate")]
        public DateTime? DemandDate { get; set; }
        [JsonProperty("actualStart")]
        public DateTime? ActualStart { get; set; }
    }

    /// <summary>
    /// 创建过程质检单请求
    /// </summary>
    public class CreateProcessInspectionRequest
    {
        public string inspectionOrderCode { get; set; }
        public string inspectionOrderName { get; set; }
        public DateTime inspectionDate { get; set; }
        public string inspector { get; set; }
        public string productionOrderCode { get; set; }
        public int dispatchId { get; set; }
        public int inspectionQuantity { get; set; }
        public int qualifiedQuantity { get; set; }
        public int unqualifiedQuantity { get; set; }
        
        // 从任务信息中获取的产品相关信息
        public string productCode { get; set; }
        public string productName { get; set; }
        public string specification { get; set; }
        public string unit { get; set; }
        public bool state { get; set; } = true; // 默认合格
    }

    /// <summary>
    /// 创建过程质检单响应
    /// </summary>
    public class CreateProcessInspectionResponse
    {
        public string msg { get; set; }
        public int code { get; set; }
        public object data { get; set; }
    }
}
